package com.lehe.controller.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lehe.common.Contants;
import com.lehe.common.enums.GoldCoinEnum;
import com.lehe.common.exceptions.LHAdminException;
import com.lehe.common.utils.StringUtil;
import com.lehe.dao.AdminUserMappingDao;
import com.lehe.dao.GoldDetailDao;
import com.lehe.dao.UserInfoDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.entry.AdminUserDto;
import com.lehe.entry.AdminUserMappingDto;
import com.lehe.entry.AdminUserSessionDto;
import com.lehe.entry.BaseDataResponse;
import com.lehe.entry.BaseResponse;
import com.lehe.entry.MyAgentDto;
import com.lehe.entry.PlayerInfoDto;
import com.lehe.entry.UserGoldDetailDto;
import com.lehe.entry.UserInfoDto;
import com.lehe.entry.page.PageDto;
import com.lehe.service.impl.AdminMenuService;
import com.lehe.service.impl.AdminRoleService;
import com.lehe.service.impl.AdminUserService;
import com.lehe.service.impl.UserManagerService;

@RequestMapping("admin/usermanager")
@Controller
public class UserManagerController extends BaseAdminController{

	@Autowired
	private UserManagerDao userManagerDao;
	@Autowired
	UserInfoDao userInfoDao;
	
	@Autowired
	private UserManagerService userManagerService;
	@Autowired
	AdminMenuService adminMenuService;
	@Autowired
	AdminRoleService adminRoleService;
	
	@Autowired
	AdminUserMappingDao adminUserMappingDao;
	
	@Autowired
	AdminUserService adminUserService;
	
	@Autowired
	GoldDetailDao goldDetailDao;
	
	@RequestMapping("myPlayer")
	public String myPlayer(@RequestParam(required=false)Long agentId,String sd,String ed,Model m){
		m.addAttribute("agentId",agentId);
		m.addAttribute("sd",sd);
		m.addAttribute("ed",ed);
		return "admin/usermanager/myPlayer";
	}
	@RequestMapping("myPlayerPay")
	public String myPlayerPay(@RequestParam(required=false)Long agentId,Model m){
		m.addAttribute("agentId",agentId);
		return "admin/usermanager/myPlayerPay";
	}
	
	@RequestMapping("myPlayerList")
	public String myPlayerData(@RequestParam(required=false)String queryStr,
			String sd,String ed,
			@RequestParam(required=false)Long agentId,
			@RequestParam(required=false)Integer page,
			@RequestParam(required=false)Integer pageSize,Model m){
		if(sd != null && sd.trim().equals("")){
			sd = null;
		}
		if(ed != null && ed.trim().equals("")){
			ed = null;
		}
		
		List<Long> ids = null;
		PageDto pd = new PageDto(page,pageSize);
		if(agentId == null){
			ids = this.getGameUserIds();
		}else{
			ids = new ArrayList<Long>();
			ids.add(agentId);
			m.addAttribute("agentId",agentId);
		}
		List<PlayerInfoDto> list = userManagerDao.queryUserPlayer(queryStr,sd,ed,ids,pd.getPageIndex(),pd.getPageSize());
		Integer count = userManagerDao.queryUserPlayerCount(queryStr,sd,ed,ids);
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryStr",queryStr);
		
		m.addAttribute("sd",sd);
		m.addAttribute("ed",ed);
		
		return "admin/usermanager/myPlayerList";
	}
	
	@RequestMapping("myPlayerListPay")
	public String myPlayerListPay(@RequestParam(required=false)String queryStr,
			@RequestParam(required=false)Long agentId,
			@RequestParam(required=false)Integer page,
			@RequestParam(required=false)Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		if(queryStr == null || queryStr.trim().equals("")){
			m.addAttribute("data",new ArrayList<PlayerInfoDto>());
			pd.setRecordCount(0);
			m.addAttribute("page",pd);
			m.addAttribute("queryStr",queryStr);
			return "admin/usermanager/myPlayerPayList";
		}

		List<PlayerInfoDto> list = userManagerDao.queryUserPlayerPay(queryStr,null,null,pd.getPageIndex(),pd.getPageSize());
		Integer count = userManagerDao.queryUserPlayerPayCount(queryStr,null,null);
		
		
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryStr",queryStr);
		return "admin/usermanager/myPlayerPayList";
	}
	/**
	 * @Description:
	* @author:wq
	* @date:2018年3月12日
	* @parameter:
	 */
	@RequestMapping("queryPlayerToPay")
	public String queryPlayerToPay(@RequestParam(required=false)String queryStr,
			@RequestParam(required=false)Integer nullity,
			@RequestParam(required=false)Long agentId,
			@RequestParam(required=false)Integer page,
			@RequestParam(required=false)Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		/*if(queryStr == null || queryStr.trim().equals("")){
			m.addAttribute("data",new ArrayList<PlayerInfoDto>());
			pd.setRecordCount(0);
			m.addAttribute("page",pd);
			m.addAttribute("queryStr",queryStr);
			return "admin/usermanager/myPlayerPayList";
		}*/
		Long roleId=this.getAdminUserRoleId(); 
		Long userId=this.getAdminUserId();
		if(1l == roleId){
			userId=null;
		}
		List<UserGoldDetailDto> list = goldDetailDao.queryPlayerToPay(queryStr,nullity,null,userId,null,null,pd.getPageIndex(),pd.getPageSize());
		Integer count = goldDetailDao.queryPlayerToPayCount(queryStr,nullity,null,userId,null,null);
		
		
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryStr",queryStr);
		m.addAttribute("nullity",nullity);
		return "admin/usermanager/myPlayerPayList";
	}
	
	
	@RequestMapping("myAgent")
	public String myAgent(){
		return "admin/usermanager/myAgent";
	}
	
	@RequestMapping("myAgentList")
	public String myAgentData(
			@RequestParam(required=false)String queryStr,
			@RequestParam(required=false)Integer page,
			@RequestParam(required=false)Long agentId,
			@RequestParam(required=false)String level,
			String sd,String ed,
			@RequestParam(required=false)String orderBy,
			@RequestParam(required=false)Integer pageSize,Model m){
		
		List<MyAgentDto> list = null;
		Integer count = null;
		PageDto pd = new PageDto(page,pageSize);
		//agentId为空，则查询关联的用户记录
		if(agentId == null){
			
			List<Long> ids = this.getGameUserIds();
			list = userManagerDao.queryUserAgentByIds(queryStr,sd,ed, ids,level, orderBy, pd.getPageIndex(), pd.getPageSize());
			count = userManagerDao.queryUserAgentByIdsCount(queryStr, null,null,ids,level);
		}else{
			list = userManagerDao.queryUserAgent(queryStr,agentId,sd,ed,level,orderBy,pd.getPageIndex(),pd.getPageSize());
			count = userManagerDao.queryUserAgentCount(queryStr,agentId,null,null,level);
		}
		
		m.addAttribute("agentId",agentId);
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryStr",queryStr);
		m.addAttribute("level",level);
		m.addAttribute("sd",sd);
		m.addAttribute("ed",ed);
		
		return "admin/usermanager/myAgentList";
	}
	
	/**
	 * 充值金币
	 */
	@RequestMapping("chargeJB")
	@ResponseBody
	public BaseResponse chargeJB(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)String goldLv,Long count,Model m){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		try {
			Double money = 0D;
			if(StringUtil.isNotBlank(goldLv)){
				GoldCoinEnum goldCoinEnum = GoldCoinEnum.valueOf(goldLv);
				count = goldCoinEnum.getCoin();
				money = goldCoinEnum.getMoney();
			}
			userManagerService.chargeJB(userId, count, money, this.getAdminUserSession());
		}catch (LHAdminException e) {
			logger.error("充值金币异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		} catch (Exception e) {
			logger.error("充值金币异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("充值金币失败");
			return resp;
		}
		return resp;
	}
	
	
	/**
	 * 充值金币
	 */
	@RequestMapping("chargeJBS")
	@ResponseBody
	public BaseResponse chargeJBS(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)String goldLv,Long count,Model m){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		try {
			Double money = 0D;
			if(StringUtil.isNotBlank(goldLv)){
				GoldCoinEnum goldCoinEnum = GoldCoinEnum.valueOf(goldLv);
				count = goldCoinEnum.getCoin();
				money = goldCoinEnum.getMoney();
			}
			userManagerService.chargeJBS(userId, count, money, this.getAdminUserSession());
		}catch (LHAdminException e) {
			logger.error("充值金币异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		} catch (Exception e) {
			logger.error("充值金币异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("充值金币失败");
			return resp;
		}
		return resp;
	}
	

	/**
	 * 运营号上充值
	 */
	@RequestMapping("chargeYYHJBS")
	@ResponseBody
	public BaseResponse chargeYYHJBS(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)String goldLv,Long count,Model m){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		try {
			Double money = 0D;
			if(StringUtil.isNotBlank(goldLv)){
				GoldCoinEnum goldCoinEnum = GoldCoinEnum.valueOf(goldLv);
				count = goldCoinEnum.getCoin();
				money = goldCoinEnum.getMoney();
			}
			userManagerService.chargeYYHJBS(userId, count, money, this.getAdminUserSession());
		}catch (LHAdminException e) {
			logger.error("运营号上充值异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		} catch (Exception e) {
			logger.error("运营号上充值异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("运营号上充值失败");
			return resp;
		}
		return resp;
	}
	
	@RequestMapping("createAgent")
	@ResponseBody
	public BaseResponse createAgent(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)Integer userLevel,
			@RequestParam(required=true)Long agentId,Model m,HttpServletRequest request){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		try {
			userManagerService.createAgent(userId, agentId,userLevel, this.getAdminUserId(), this.getAdminUserSession().getRoleId());
		
			
			String userName = this.getAdminUserSession().getAccount();
			AdminUserDto adminUserDto = adminUserService.queryByAccount(userName);
			AdminUserSessionDto sessionDto = new AdminUserSessionDto();
			BeanUtils.copyProperties(adminUserDto, sessionDto);
			String[] ids = adminRoleService.queryById(sessionDto.getRoleId()).getMenuIds().split(",");
			sessionDto.setMenuDtoList(adminMenuService.queryMenusByIds(ids));
			if(StringUtil.isNotBlank(sessionDto.getUserIds())){
				sessionDto.setUserInfoDtoList(userInfoDao.queryUserInfos(Arrays.asList(sessionDto.getUserIds().split(","))));
			}
			request.getSession().setAttribute(Contants.SESSION_ADMIN_USER_KEY, sessionDto);
			
			
		} catch (LHAdminException e) {
			logger.error("创建代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		}catch (Exception e) {
			logger.error("创建代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("发生未知错误");
			return resp;
		}
		return resp;
	}
	
	@RequestMapping("confrimDeleteAgent")
	@ResponseBody
	public BaseResponse confrimDeleteAgent(
			@RequestParam(required=true)Long userId,Model m,HttpServletRequest request){
		
		BaseDataResponse resp = new BaseDataResponse(BaseResponse.SUCCESS,"");
		try {
			
			if(userId == null){
				throw new LHAdminException("请输入用户id");
			}
			
			List<String> ids = new ArrayList<String>();
			ids.add(userId.toString());
			List<UserInfoDto> tmp = userInfoDao.queryUserInfos(ids);
			
			if(tmp == null || tmp.isEmpty()){
				throw new LHAdminException("要解除代理的用户不存在【"+userId+"】");
			}
			
			UserInfoDto user = tmp.get(0);
			
			if(user.getAgentId() == null || user.getAgentId().intValue() == 0){
				throw new LHAdminException("要解除代理的用户还不是代理");
			}
			
			if(user.getAgentId() == null || user.getAgentId().intValue() == 0){
				throw new LHAdminException("要解除代理的用户还不是代理");
			}
			//查询下属代理个数
			Integer count = userManagerDao.queryUserAgentCount(null,user.getAgentId(),null,null,null);
			if(count > 0){
				throw new LHAdminException("要解除代理的用户已经有"+count+"个下属代理，不能解除");
			}
			
			if(!this.getAdminUserRoleId().equals(1L)){
				throw new LHAdminException("只有系统管理员才有权限解除代理");
			}
			
			//查询下属玩家个数
			List<Long> tmpIds = new ArrayList<Long>();
			tmpIds.add(userId);
			count = userManagerDao.queryUserPlayerCount(null,null,null,tmpIds);
			if(count > 0){
				throw new LHAdminException("要解除代理的用户已经有"+count+"个下属玩家，不能解除");
			}
			
			AdminUserMappingDto mapping = adminUserMappingDao.queryByUserId(userId);
			
			Map<String,Object> data = new HashMap<String,Object>();
			
			if(mapping != null){
				AdminUserDto adminUser = adminUserService.queryById(mapping.getAdminUserId());
				if(adminUser != null){
					adminUser.setPwd("");
					data.put("adminUser",adminUser);
				}
			}
			
			UserInfoDto groupUser = userInfoDao.queryUserInfoByAgentId(user.getGroupId());
			UserInfoDto extUserInfo = userInfoDao.queryUserInfoByAgentId(user.getAgentId());
			if(extUserInfo != null){
				user = extUserInfo;
			}
			
			
			data.put("userInfo",user);
			data.put("groupUser",groupUser);
			resp.setData(data);
			
		} catch (LHAdminException e) {
			logger.error("确认解除代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		}catch (Exception e) {
			logger.error("确认解除代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("发生未知错误");
			return resp;
		}
		
		return resp;
	}
	
	@RequestMapping("deleteAgent")
	@ResponseBody
	public BaseResponse deleteAgent(
			@RequestParam(required=true)Long userId,Model m,HttpServletRequest request){
		BaseDataResponse resp = new BaseDataResponse(BaseResponse.SUCCESS,"");
		try {
			
			if(userId == null){
				throw new LHAdminException("请输入用户id");
			}
			
			if(!this.getAdminUserRoleId().equals(1L)){
				throw new LHAdminException("只有系统管理员才有权限解除代理");
			}
			
			userManagerService.deleteAgent(userId);
			
		} catch (LHAdminException e) {
			logger.error("解除代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(e.getMessage());
			return resp;
		}catch (Exception e) {
			logger.error("解除代理发生异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg("发生未知错误");
			return resp;
		}
		
		return resp;
	}
	
	@RequestMapping("userVipSet")
	public String userVipSet(@RequestParam(required=false)Long agentId,Model m){
		m.addAttribute("agentId",agentId);
		return "admin/usermanager/userVipSet";
	}
	
	/**
	 * @Description:
	* @author:wq
	* @date:2018年3月12日
	* @parameter:
	 */
	@RequestMapping("queryUserVipSet")
	public String queryUserVipSet(@RequestParam(required=false)String queryStr,
			@RequestParam(required=false)Integer memberOrder,
			@RequestParam(required=false)Long agentId,
			@RequestParam(required=false)Integer page,
			@RequestParam(required=false)Integer pageSize,Model m){
		PageDto pd = new PageDto(page,pageSize);
		
		/*if(queryStr == null || queryStr.trim().equals("")){
			m.addAttribute("data",new ArrayList<PlayerInfoDto>());
			pd.setRecordCount(0);
			m.addAttribute("page",pd);
			m.addAttribute("queryStr",queryStr);
			return "admin/usermanager/userVipSetList";
		}*/
		Long roleId=this.getAdminUserRoleId(); 
		Long userId=this.getAdminUserId();
		if(1l == roleId){
			userId=null;
		}
		List<UserGoldDetailDto> list = goldDetailDao.queryPlayerToPay(queryStr,null,memberOrder,userId,null,null,pd.getPageIndex(),pd.getPageSize());
		Integer count = goldDetailDao.queryPlayerToPayCount(queryStr,null,memberOrder,userId,null,null);
		
		
		m.addAttribute("data",list);
		pd.setRecordCount(count);
		m.addAttribute("page",pd);
		m.addAttribute("queryStr",queryStr);
		m.addAttribute("memberOrder",memberOrder);
		return "admin/usermanager/userVipSetList";
	}
	
	
	/**
	 * 设置VIP
	 */
	@RequestMapping("userVip")
	@ResponseBody
	public BaseResponse userVip(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)Integer vip,Model m){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		String str=vip==1?"设置VIP":"取消VIP";
		try {
			goldDetailDao.userVip(userId, vip);
		}catch (Exception e) {
			logger.error(str+"异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(str+"失败");
			return resp;
		}
		return resp;
	}
	
	/**
	 * 封禁
	 */
	@RequestMapping("setNullity")
	@ResponseBody
	public BaseResponse setNullity(
			@RequestParam(required=true)Long userId,
			@RequestParam(required=true)Integer nullity,Model m){
		
		BaseResponse resp = new BaseResponse(BaseResponse.SUCCESS,"");
		String str=nullity==1?"封停":"解封";
		try {			
			goldDetailDao.setNullity(userId, nullity);
		}catch (Exception e) {
			logger.error(str+"异常", e);
			resp.setCode(BaseResponse.FAIL);
			resp.setMsg(str+"失败");
			return resp;
		}
		return resp;
	}
	
	
}
